package com.git.hui.yinshua.biz.util;

import com.alibaba.fastjson.JSONObject;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.net.URLEncoder;

/**
 * @author YiHui
 * @date 2024/5/30
 */
@Slf4j
public class QiNiuUtil {
    // 10分钟，可以自定义链接过期时间
    private static final Long EXPIRE_IN_SECONDS = 600L;
    private static Auth auth;

    static {
        String accessKey = "SU6AAHyhUGiVfZ5d_P9Z6AJe1GzbRi5EFO3gYh07";
        String secretKey = "_HH84J2OpVpP1WsYI94dr0Dgtvap6N7AbVF31nZF";
        auth = Auth.create(accessKey, secretKey);
    }

    public static String sign(String url) {
        if (!url.startsWith("http://ql.hhui.top")) {
            return url;
        }

        if (url.indexOf("?") > 0) {
            // 已经签过名了，直接返回
            return url;
        }

        try {
            URL u = new URL(url);
            String domain = u.getHost();
            String path = u.getPath();
            return buildSignUrl(domain, path);
        } catch (Exception e) {
            log.error("签名异常: {}", url, e);
            return url;
        }
    }

    public static String buildSignUrl(String domain, String fileName) {
        try {
            String domainOfBucket = domain.startsWith("http") ? domain : "http://" + domain;
            if (!domainOfBucket.endsWith("/")) {
                domainOfBucket = domainOfBucket + "/";
            }
            if (fileName.startsWith("/")) {
                fileName = fileName.substring(1);
            }
            String encodedFileName = URLEncoder.encode(fileName, "utf-8").replace("+", "%20").replace("%2F", "/");
            String publicUrl = String.format("%s%s", domainOfBucket, encodedFileName);
            return auth.privateDownloadUrl(publicUrl, EXPIRE_IN_SECONDS);
        } catch (Exception e) {
            return null;
        }
    }

    public static String buildUploadToken() {
        String scope = "img-yhh:yinshua/";
        Long deadLine = System.currentTimeMillis() / 1000 + 7200;
        String returnBody = "{\n" +
                "      \"size\": $(fsize),\n" +
                "      \"w\": $(imageInfo.width),\n" +
                "      \"h\": $(imageInfo.height),\n" +
                "      \"hash\": $(etag)\n" +
                "}";
        StringMap obj = new StringMap();
        obj.put("scope", scope);
        obj.put("deadline", deadLine);
        obj.put("returnBody", returnBody);

        String upToken = auth.uploadToken("img-yhh", null, 7200, obj);
        System.out.println(upToken);
        return upToken;
    }

    public static void main(String[] args) {
        String fileName = "http://ql.hhui.top/poetry/9/391_0.jpg";
        String ans = sign(fileName);
        System.out.println(ans);


        System.out.println("token:\n" + buildUploadToken());
    }

}
